package pro.shuangxi.model.downfile.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mybatisplus.pojo.DownFileTask;
import mybatisplus.pojo.DownFileTaskLink;
import mybatisplus.service.IDownFileTaskLinkService;
import mybatisplus.service.IDownFileTaskService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pro.shuangxi.common.vo.PageVo;
import pro.shuangxi.common.vo.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mengshx
 * @since 2022-06-25
 */
@RestController
@RequestMapping("/downFileTaskLink")
public class DownFileTaskLinkController {
    @Autowired
    IDownFileTaskLinkService downFileTaskLinkService;
    @Autowired
    IDownFileTaskService downFileTaskService;
    @RequestMapping("page.do")
    public Result page(PageVo pageVo,String id) throws Exception{
        QueryWrapper<DownFileTaskLink> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", id);
        Page page = downFileTaskLinkService.page(pageVo.getLayuiPage(), wrapper);
        return Result.OK(page);
    }
    @RequestMapping("download.do")
    public void download(HttpServletResponse response, String id) throws Exception{
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        DownFileTaskLink link = downFileTaskLinkService.getById(id);
        String taskLink = link.getTaskLink();
        DownFileTask task = downFileTaskService.getById(link.getTaskId());
        URI host = URLUtil.getHost(new URL(task.getTargetUrl()));
        HttpRequest httpRequest = HttpUtil.createGet(taskLink);

        httpRequest.header("Referer",host.toString());
        HttpResponse execute = httpRequest.execute();
        InputStream inputStream = execute.bodyStream();
        IoUtil.copy(inputStream, response.getOutputStream());
    }
    @RequestMapping("downAll.do")
    public void downAll(HttpServletResponse response, String taskId) throws Exception{
        long time = new Date().getTime();
//        File file = new File("/temp/shuangxi/zip/" + time + ".zip");
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        DownFileTask task = downFileTaskService.getById(taskId);
        URI host = URLUtil.getHost(new URL(task.getTargetUrl()));
        List<DownFileTaskLink> list = downFileTaskLinkService.list(new QueryWrapper<DownFileTaskLink>().eq("task_id", taskId));
        for (int i = 0; i < list.size(); i++) {

            DownFileTaskLink link = list.get(i);
            try {
                String name = link.getTaskLink().substring(link.getTaskLink().lastIndexOf("/") + 1);
                zipOutputStream.putNextEntry(new ZipEntry(name));
                HttpRequest httpRequest = HttpUtil.createGet(link.getTaskLink());
                httpRequest.header("Referer",host.toString());
                HttpResponse execute = httpRequest.execute();
                InputStream inputStream = execute.bodyStream();
                byte[] bytes = IoUtil.readBytes(inputStream);
                IoUtil.write( zipOutputStream,false,bytes);
                IOUtils.closeQuietly(inputStream);
                zipOutputStream.flush();
                zipOutputStream.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        zipOutputStream.flush();
        IOUtils.closeQuietly(zipOutputStream);
        byte[] data = outputStream.toByteArray();
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"All.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(),true,data);
    }


}
